import React, { useEffect, useState } from 'react';
import { Modal, Form, Input, Select, DatePicker, Switch, message, Alert, Space, Button } from 'antd';
import { EyeOutlined } from '@ant-design/icons';
import { createNotification, updateNotification, previewNotification } from '@/services/systemManagementApi';
import moment from 'moment';

interface NotificationFormProps {
  visible: boolean;
  mode: 'create' | 'edit';
  initialValues?: SYSTEM.NotificationModel;
  onCancel: () => void;
  onSuccess: () => void;
}

const NotificationForm: React.FC<NotificationFormProps> = ({
  visible,
  mode,
  initialValues,
  onCancel,
  onSuccess,
}) => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [previewLoading, setPreviewLoading] = useState(false);
  const [previewData, setPreviewData] = useState<any>(null);
  const [sendImmediately, setSendImmediately] = useState(false);

  useEffect(() => {
    if (visible) {
      if (mode === 'edit' && initialValues) {
        const formData = {
          ...initialValues,
          scheduled_time: initialValues.scheduled_time ? moment(initialValues.scheduled_time) : undefined,
        };
        form.setFieldsValue(formData);
        setSendImmediately(initialValues.status === 'sent');
      } else {
        form.resetFields();
        setSendImmediately(false);
        setPreviewData(null);
      }
    }
  }, [visible, mode, initialValues, form]);

  // 处理表单提交
  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      setLoading(true);

      const submitData = {
        ...values,
        scheduled_time: values.scheduled_time ? values.scheduled_time.format('YYYY-MM-DD HH:mm:ss') : undefined,
        status: sendImmediately ? 'sent' : (values.scheduled_time ? 'scheduled' : 'draft'),
      };

      if (mode === 'create') {
        await createNotification(submitData);
        message.success('通知创建成功');
      } else {
        await updateNotification(initialValues!.id, submitData);
        message.success('通知更新成功');
      }

      onSuccess();
    } catch (error) {
      message.error(mode === 'create' ? '通知创建失败' : '通知更新失败');
    } finally {
      setLoading(false);
    }
  };

  // 处理预览
  const handlePreview = async () => {
    try {
      const values = await form.validateFields();
      setPreviewLoading(true);

      const response = await previewNotification(values);
      setPreviewData(response.data);
    } catch (error) {
      message.error('预览失败');
    } finally {
      setPreviewLoading(false);
    }
  };

  // 监听目标类型变化
  const handleTargetTypeChange = (value: string) => {
    if (value === 'all') {
      form.setFieldsValue({ target_value: undefined });
    }
  };

  return (
    <Modal
      title={mode === 'create' ? '新建通知' : '编辑通知'}
      open={visible}
      onCancel={onCancel}
      onOk={handleSubmit}
      confirmLoading={loading}
      width={800}
      destroyOnClose
    >
      <Form
        form={form}
        layout="vertical"
        initialValues={{
          type: 'system',
          target_type: 'all',
          status: 'draft',
        }}
      >
        <Form.Item
          name="title"
          label="通知标题"
          rules={[
            { required: true, message: '请输入通知标题' },
            { max: 100, message: '标题不能超过100个字符' },
          ]}
        >
          <Input placeholder="请输入通知标题" />
        </Form.Item>

        <Form.Item
          name="content"
          label="通知内容"
          rules={[
            { required: true, message: '请输入通知内容' },
            { max: 1000, message: '内容不能超过1000个字符' },
          ]}
        >
          <Input.TextArea
            rows={6}
            placeholder="请输入通知内容"
            showCount
            maxLength={1000}
          />
        </Form.Item>

        <Form.Item
          name="type"
          label="通知类型"
          rules={[{ required: true, message: '请选择通知类型' }]}
        >
          <Select placeholder="请选择通知类型">
            <Select.Option value="system">系统通知</Select.Option>
            <Select.Option value="announcement">公告通知</Select.Option>
            <Select.Option value="maintenance">维护通知</Select.Option>
            <Select.Option value="promotion">推广通知</Select.Option>
          </Select>
        </Form.Item>

        <Form.Item
          name="target_type"
          label="目标用户"
          rules={[{ required: true, message: '请选择目标用户' }]}
        >
          <Select placeholder="请选择目标用户" onChange={handleTargetTypeChange}>
            <Select.Option value="all">全部用户</Select.Option>
            <Select.Option value="role">指定角色</Select.Option>
            <Select.Option value="user">指定用户</Select.Option>
          </Select>
        </Form.Item>

        <Form.Item
          noStyle
          shouldUpdate={(prevValues, currentValues) => 
            prevValues.target_type !== currentValues.target_type
          }
        >
          {({ getFieldValue }) => {
            const targetType = getFieldValue('target_type');
            if (targetType === 'role') {
              return (
                <Form.Item
                  name="target_value"
                  label="目标角色"
                  rules={[{ required: true, message: '请选择目标角色' }]}
                >
                  <Select placeholder="请选择目标角色" mode="multiple">
                    <Select.Option value="admin">管理员</Select.Option>
                    <Select.Option value="teacher">教师</Select.Option>
                    <Select.Option value="user">普通用户</Select.Option>
                  </Select>
                </Form.Item>
              );
            }
            if (targetType === 'user') {
              return (
                <Form.Item
                  name="target_value"
                  label="目标用户ID"
                  rules={[{ required: true, message: '请输入目标用户ID' }]}
                >
                  <Input.TextArea
                    rows={3}
                    placeholder="请输入用户ID，多个用户用逗号分隔，如：1,2,3"
                  />
                </Form.Item>
              );
            }
            return null;
          }}
        </Form.Item>

        <Form.Item label="发送设置">
          <Space direction="vertical" style={{ width: '100%' }}>
            <div>
              <Switch
                checked={sendImmediately}
                onChange={setSendImmediately}
                disabled={mode === 'edit' && initialValues?.status === 'sent'}
              />
              <span style={{ marginLeft: 8 }}>立即发送</span>
            </div>
            
            {!sendImmediately && (
              <Form.Item
                name="scheduled_time"
                label="排期时间"
                style={{ marginBottom: 0 }}
              >
                <DatePicker
                  showTime
                  placeholder="选择发送时间"
                  style={{ width: '100%' }}
                  disabledDate={(current) => current && current < moment().startOf('day')}
                />
              </Form.Item>
            )}
          </Space>
        </Form.Item>

        {/* 预览按钮 */}
        <Form.Item>
          <Button
            type="dashed"
            icon={<EyeOutlined />}
            onClick={handlePreview}
            loading={previewLoading}
            style={{ width: '100%' }}
          >
            预览通知效果
          </Button>
        </Form.Item>

        {/* 预览结果 */}
        {previewData && (
          <Alert
            message="预览结果"
            description={
              <div>
                <p><strong>预计接收人数：</strong>{previewData.recipient_count} 人</p>
                <div style={{ 
                  marginTop: 12, 
                  padding: 16, 
                  background: '#f5f5f5', 
                  borderRadius: 4,
                  border: '1px solid #d9d9d9'
                }}>
                  <div style={{ fontWeight: 'bold', marginBottom: 8 }}>通知预览：</div>
                  <div dangerouslySetInnerHTML={{ __html: previewData.preview_html }} />
                </div>
              </div>
            }
            type="info"
            showIcon
            style={{ marginTop: 16 }}
          />
        )}

        {/* 发送提示 */}
        {sendImmediately && (
          <Alert
            message="立即发送提醒"
            description="选择立即发送后，通知将在保存时立即发送给目标用户，发送后将无法修改。"
            type="warning"
            showIcon
            style={{ marginTop: 16 }}
          />
        )}
      </Form>
    </Modal>
  );
};

export default NotificationForm;
